package com.frogs.ucenter.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.component.cache.Cache;
import com.frogs.framework.util.DWZResponse;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.RenderUtil;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.file.FileUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.GoodsEvaluateEnum;
import com.frogs.ucenter.entity.GoodsEvaluate;
import com.frogs.ucenter.entity.GoodsEvaluateOperLog;
import com.frogs.ucenter.export.ImportGoodsEvaluateData;
import com.frogs.ucenter.service.GoodsEvaluateOperLogService;
import com.frogs.ucenter.service.GoodsEvaluateService;
import com.frogs.ucenter.util.DataCacheKey;

@Controller
@RequestMapping("/admin/goodsEvaluate")
public class GoodsEvaluateController extends BaseController3 {
    private static final String ROOT_VIEW = "admin/goodsEvaluate";
    
    private static final String DESC = "/desc";

    private static final String HOME_VIEW = "admin/goodsEvaluate/home";

    private static final String EDIT_VIEW = "admin/goodsEvaluate/edit";
    
    private static final String DESC_VIEW = "admin/goodsEvaluate/desc";
    
    private static final String IMPORT_VIEW = ROOT_VIEW + "/import";
    
    private static String IMPORT_EVALUATE_PATH = "";
    
    @Resource(name="xmemcached")
	public Cache cache;

    @Autowired
    private GoodsEvaluateService goodsEvaluateService;
    
    @Autowired
    private GoodsEvaluateOperLogService goodsEvaluateOperLogService;
    
    @Resource
    private ImportGoodsEvaluateData importGoodsEvaluateData;

    @RequestMapping()
    public String listGoodsEvaluate(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, true );
        model.put("orderByClause", "create_time desc");
        getPageList( model );
        return HOME_VIEW;
    }

    @RequestMapping(EDIT)
    public String createGoodsEvaluate(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.put( "model",goodsEvaluateService.getById( id ) ); 
        }
        return EDIT_VIEW;
    }
    
    @RequestMapping(DESC)
    public String createGoodsEvaluateDesc(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.put( "model",goodsEvaluateService.getById( id ) ); 
        }
        return DESC_VIEW;
    }

    @RequestMapping(ADD)
    public String saveGoodsEvaluate(HttpServletRequest request, HttpServletResponse response, ModelMap model, GoodsEvaluate goodsEvaluate) {
    	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
    	setRequestModelMap(request, model, false);
        DWZResponse.Builder builder;
        try {
        	GoodsEvaluateOperLog goodsEvaluateOperLog = new GoodsEvaluateOperLog();
        	goodsEvaluateOperLog.setCreateTime(new Date());
        	goodsEvaluateOperLog.setGoodsEvaluateCommentId(0);
        	goodsEvaluateOperLog.setGoodsEvaluateId(goodsEvaluate.getId());
        	goodsEvaluateOperLog.setOperDesc(reqInfo.getParameter("nopassdesc", null));
        	goodsEvaluateOperLogService.insert(goodsEvaluateOperLog);
            builder = DWZResponse.getSucessBuilder("操作成功！");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("fail" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        return null;
    }

    @RequestMapping(SHOW)
    public String showGoodsEvaluate(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.addAttribute( goodsEvaluateService.getById( id ) ); 
        }
        setRequestModelMap(request, model);
        return null;
    }

    @RequestMapping(UPDATE)
    public String updateGoodsEvaluate(HttpServletRequest request, HttpServletResponse response, ModelMap model, GoodsEvaluate goodsEvaluateNew) throws Exception {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            DWZResponse.Builder builder;
            try {
                GoodsEvaluate goodsEvaluate = goodsEvaluateService.getById( id ); 
                PropertyUtils.copyProperties(goodsEvaluate, goodsEvaluateNew);
                goodsEvaluateService.update( goodsEvaluate ); 
                model.clear();
                builder = DWZResponse.getSucessBuilder("success");
            } catch (Exception e) {
                builder = DWZResponse.getFailBuilder("fail" + e.getMessage());
            }
            RenderUtil.renderHtml(builder.build().toString(), response);
        }
        return null;
    }

    @RequestMapping(AUDIT)
    public String auditGoodsEvaluate(HttpServletRequest request, HttpServletResponse response, ModelMap model, String ids) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = reqInfo.getIntParameter( "status", -1 );
        
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        try {
        	String[] idArray = ids.split(",");
            model.put("inIdList", idArray);
            int row = goodsEvaluateService.update( model );
            if (row > 0) {
            	Map<String, Object> params = new HashMap<String, Object>();
            	params.put("inIdList", idArray);
            	PageList<GoodsEvaluate> list = goodsEvaluateService.getList(params, 1, 1000);
            	List<Integer> goodsIds = new ArrayList<Integer>();
            	for (GoodsEvaluate goodsEvaluate : list) {
            		goodsIds.add(goodsEvaluate.getGoodsId());
            		cleanEvaluateCache(goodsEvaluate.getUserId(), null);
				}
            	cleanEvaluateCache(null, goodsIds);
            }
            builder = DWZResponse.getSucessBuilder("操作成功！");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("操作失败：" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        return null;
    }

    @RequestMapping(DELETE)
    public String deleteGoodsEvaluate(HttpServletRequest request, HttpServletResponse response, ModelMap model, String inIdList) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            goodsEvaluateService.delete( model ); 
            builder = DWZResponse.getSucessBuilder("操作成功！");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("操作失败：" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        return null;
    }
    
    @RequestMapping("/import")
    public String importFile(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    	setRequestModelMap(request, model);
    	return IMPORT_VIEW;
    }
    
    @RequestMapping("/fileReceive")
    public String filerReceive(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    	setRequestModelMap(request, model);
    	DWZResponse.Builder builder;
    	MultipartRequest mulRequest = (MultipartRequest)request;
    	MultipartFile file = mulRequest.getFile("file");
    	if (file == null) {
    		 builder = DWZResponse.getFailBuilder("上传文件不能为空");
    		 RenderUtil.renderHtml(builder.build().toString(), response);
    		 return null;
    	}
    	String ext = FileUtil.getFileType(file.getOriginalFilename());
    	if (!("xls".equals(ext) || "xlsx".equals(ext))) {
    		 builder = DWZResponse.getFailBuilder("上传文件格式不对，必须为.xls或.xlsx格式");
    		 RenderUtil.renderHtml(builder.build().toString(), response);
    		 return null;
    	}
    	String path = request.getRealPath("/");
    	String fileName = path + "/import/evaluate" + System.currentTimeMillis() + "." + ext;
    	IMPORT_EVALUATE_PATH = fileName;
    	File newfile = new File(fileName);
        
    	try {
			file.transferTo(newfile);
			builder = DWZResponse.getSucessBuilder("操作成功！");
		} catch (Exception e) {
			builder = DWZResponse.getFailBuilder("操作失败：" + e.getMessage());
		}
		RenderUtil.renderHtml(builder.build().toString(), response);
		return null;
    }
    
    @RequestMapping("/importEvaluate")
    public String importEvaluate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
    	String startDate = reqInfo.getParameter("startDate", "2014-03-01");
    	String endDate = reqInfo.getParameter("endDate", "2014-08-22");
    	setRequestModelMap(request, model);
    	DWZResponse.Builder builder;
    	if (StringUtil.isEmpty(IMPORT_EVALUATE_PATH)) {
    		builder = DWZResponse.getFailBuilder("先上传文件");
   		 	RenderUtil.renderHtml(builder.build().toString(), response);
   		 	return null;
    	}
    	Map<String, Object> result = importGoodsEvaluateData.verifyForm(IMPORT_EVALUATE_PATH);
    	if ((Integer) result.get("code") == 0) {
    		builder = DWZResponse.getFailBuilder((String) result.get("msg"));
   		 	RenderUtil.renderHtml(builder.build().toString(), response);
   		 	return null;
    	}
    	importGoodsEvaluateData.importIn(IMPORT_EVALUATE_PATH, startDate, endDate);
    	IMPORT_EVALUATE_PATH = "";
    	builder = DWZResponse.getSucessBuilder("执行成功！该导入是异步执行，请稍后查询评价列表");
    	RenderUtil.renderHtml(builder.build().toString(), response);
    	return null;
    }

    private PageList<GoodsEvaluate> getPageList(ModelMap model) {
        PageList<GoodsEvaluate> goodsEvaluateList = goodsEvaluateService.getList( model, Integer.parseInt(model.get("pageNum").toString()), Integer.parseInt(model.get("numPerPage").toString()) ); 
        model.put("goodsEvaluateList",goodsEvaluateList);
        model.put("pageTurn",goodsEvaluateList.getPageTurn());
        return goodsEvaluateList;
    }
    
    @Async
	private void cleanEvaluateCache(Integer userId , List<Integer> goodsIds ){
    	if (userId != null) {
    		this.cleanEvaluateCacheByUserId(userId);
    	}
		if (goodsIds != null) {
			this.cleanEvaluateCacheByGoodsIds(goodsIds);
		}
	}
	
	private void cleanEvaluateCacheByUserId(Integer userId) {
		StringBuilder mapKey = new StringBuilder();
		List<Integer> sortList = GoodsEvaluateEnum.getSortList();
		for (Integer id : sortList) {
			mapKey.setLength(0);
			mapKey.append(DataCacheKey.goodsEvaluateMapKey);
			mapKey.append("_USER_").append(userId);
			mapKey.append("_SORT_").append(id);
			cache.remove(mapKey.toString());
		}
		
	}
	
	private void cleanEvaluateCacheByGoodsIds(List<Integer> goodsIds ){
		StringBuilder mapKey = new StringBuilder();
		if (goodsIds != null) {
			for (int i=0; i<goodsIds.size(); i++) {
			    
				List<Integer> sortList = GoodsEvaluateEnum.getSortList();
				for (Integer id : sortList) {
					mapKey.setLength(0);
					mapKey.append(DataCacheKey.goodsEvaluateMapKey);
					mapKey.append("_GOODS_").append(goodsIds.get(i));
					mapKey.append("_SORT_").append(id);
					cache.remove(mapKey.toString());
				}
			}
		}
	}
}